<template>
  <el-dialog top="50px" title="修改患者信息" width="800px" :visible.sync="patBasicInfoVisible" @close="onClose" :close-on-click-modal="true" :destroy-on-close="true">
    <div class="dialog-form-con" style="margin-top:-20px;margin-left: -20px;">
      <el-form label-width="110px" :model="formdata" ref="formdata" :rules="rules" :loading="loading">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="患者姓名" prop="patName">
              <el-input size="small" v-model="formdata.patName" @change="nameChange" placeholder="请输入内容" @input="nameInput"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="身份证号" prop="idCard">
              <!-- <el-input size="small" v-model="formdata.idCard" placeholder="身份证" @change="idCardChange" @input="handleInput" @paste.native="copy"></el-input> -->
              <el-input size="small" v-model="formdata.idCard" placeholder="身份证" @paste.native="copy"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="姓名拼音" prop="nameEnglish">
              <el-input size="small" v-model="formdata.nameEnglish" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formdata.gender">
                <el-radio :label="1" style="margin-right: 4px;">男</el-radio>
                <el-radio :label="2" style="margin-right: 4px;">女</el-radio>
                <el-radio :label="9" style="margin-right: 4px;">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" style="clear: both;">
            <el-form-item label="年龄" prop="patAge">
              <el-input size="small" ref="patAge" v-model="formdata.patAge" @change="ageChange" placeholder="年龄">
                <!-- <el-select
                  v-model="formdata.patientAgeUnit"
                  slot="append"
                  @change="ageChange"
                  style="width: 60px;"
                >
                  <el-option
                    label="岁"
                    value="Y"
                  ></el-option>
                  <el-option
                    label="月"
                    value="M"
                  ></el-option>
                  <el-option
                    label="天"
                    value="D"
                  ></el-option>
                </el-select> -->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                size="small"
                ref="birthDate"
                v-model="formdata.birthDate"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
                style="width: 100%;"
                @change="birthDateChange"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" style="clear: both;">
            <el-form-item label="预约医院" prop="hospitalName">
              <el-input size="small" v-model="formdata.hospitalName" disabled="disabled" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="访问号" prop="accessNo">
              <el-input size="small" v-model="formdata.accessNo" disabled="disabled" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="患者电话" prop="patTelephone">
              <el-input size="small" v-model="formdata.patTelephone" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="病区" prop="wardName">
              <el-input size="small" v-model="formdata.wardName" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="床号" prop="bedno">
              <el-input size="small" v-model="formdata.bedno" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="价格" prop="price">
              <el-input size="small" v-model="formdata.price" placeholder="请输入内容" @input="priceInput"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="申请科室" prop="sqdep">
              <el-input size="small" v-model="formdata.sqdep" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="申请科室代码" prop="sqdepCode">
              <el-input size="small" v-model="formdata.sqdepCode" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="申请医生" prop="doctor">
              <el-input size="small" v-model="formdata.doctor" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="申请医生代码" prop="doctorCode">
              <el-input size="small" v-model="formdata.doctorCode" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="检查医生" prop="doctor" v-if="formdata.dep === '内窥镜'">
              <el-select v-model="formdata.radioDoctor" filterable allow-create clearable style="width: 100%;">
                <el-option
                  v-for="item in radioDoctorOptions"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
              <!-- <el-input size="small" v-model="formdata.radioDoctor" placeholder="请输入内容"></el-input> -->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="预估类型" prop="doctorCode" v-if="formdata.dep === '内窥镜'">
              <el-select v-model="formdata.treatmentType" filterable clearable allow-create style="width: 100%;">
                <el-option
                  v-for="item in treatmentTypeOptions"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
              <!-- <el-input size="small" v-model="formdata." placeholder="请输入内容"></el-input> -->
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="保密级别" prop="doctor" v-permission="'YJYY10008051'">
              <el-select size="mini" ref="examClass" v-model="formdata.privacyLevel" filterable style="width:120px;" clearable>
                <el-option
                  v-for="(item, index) in privacyLevelList"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注" prop="exammark">
              <el-input type="textarea" size="small" v-model="formdata.exammark" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="isSendParam || isRequiredItems">
            <el-form-item label="临床诊断" prop="clinicdiagnosis">
              <el-input type="textarea" size="small" v-model="formdata.clinicdiagnosis" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="isSendParam || isRequiredItems">
            <el-form-item label="病史" prop="diseasesHistory">
              <el-input type="textarea" size="small" v-model="formdata.diseasesHistory" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="text-align:right">
            <el-button type="primary" @click="submitForm('formdata')">修改</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import { changepatexam, getItemGroupList } from '@/api/api.js'
import { mapGetters } from 'vuex'
import {
  dateFormatter,
  isIdCard,
  sexById,
  birthdayById,
  birthdayByAge
} from '@/utils/validate'
export default {
  props: {
    hospitalCode: {
      String,
      default: ''
    }
  },
  data() {
    return {
      applyInfoHospital: window.g.applyInfoHospital,
      // privacyLevelList: [],
      patBasicInfoVisible: false,
      isSendParam: window.g.isSendParam,
      formdata: {
        hospitalName: '',
        accessNo: '',
        patName: '',
        gender: '',
        patAge: '',
        patientAgeUnit: 'Y',
        patientAge: '',
        birthDate: '',
        patTelephone: '',
        wardName: '',
        idCard: '',
        wardno: '',
        wardnoCode: '',
        sqdep: '',
        sqdepCode: '',
        doctor: '',
        doctorCode: '',
        bedno: '',
        // 新增字段
        nameEnglish: '',
        price: 0.0,
        exammark: '',
        clinicdiagnosis: '',
        diseasesHistory: '',
        privacyLevel: '',
        radioDoctor: '', // 检查医生
        treatmentType: '', // 治疗类型
        patBirthday: ''
      },
      loading: true,
      treatmentTypeOptions: [],
      radioDoctorOptions: [],
      pickerOptions: {
        disabledDate(time) {
          // 这个是当前日期后的日期不可选
          return time.getTime() > Date.now()
        }
      },
      rules: {
        patName: [
          { required: true, message: '患者姓名不能为空', trigger: 'blur' }
        ],
        // idCard: [
        //   { required: true, message: '身份证号码不能为空', trigger: 'blur' },
        //   { min: 15, max: 18, message: '长度在 15 到 18 个字符', trigger: 'blur' }
        // ],
        hospitalCode: [
          { required: true, message: '预约医院代码不能为空', trigger: 'blur' }
        ],
        accessNo: [
          { required: true, message: '访问号不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请填写正确的金额(小数点后保留两位)', pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/ }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['privacyLevelList']),
    appConfig() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig
    },
    isRequiredItems() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isRequiredItems
    }
  },
  mounted() {
    window.focus()
    this.getTreatmentType()
    this.getRadioDoctor()
    // this.getPrivacyLevel()
  },
  beforeDestroy() {
    console.log('编辑记录页面销毁')
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    // async getPrivacyLevel() {
    //   console.log('patBasicInfo.vue=>获取保密级别')
    //   let params = { HospitalCode: this.hospitalCode, type: '保密级别' }
    //   await this.$store.dispatch('settings/set_privacyLevelList', params)
    //   console.log('this.privacyLevelList', this.privacyLevelList)
    // },
    checkInfo(iden) {
      let val = iden.length
      let sex = null
      let birth = null
      let myDate = new Date()
      let month = myDate.getMonth() + 1
      let day = myDate.getDate()
      let age = 0
      let getMonth = 0
      // 身份证验证
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!reg.test(iden)) {
        this.$message.error('身份证号码不正确!')
        return
      }
      // 根据身份证获取相关信息
      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1
        sex = iden.substring(16, 17)
        birth = iden.substring(6, 10) + '-' + iden.substring(10, 12) + '-' + iden.substring(12, 14)
        getMonth = iden.substring(6, 10) + '-' + iden.substring(10, 12)
        if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++
      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901
        sex = iden.substring(13, 14)
        birth = '19' + iden.substring(6, 8) + '-' + iden.substring(8, 10) + '-' + iden.substring(10, 12)
        getMonth = '19' + iden.substring(6, 8) + '-' + iden.substring(8, 10)
        if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++
      }
      if (sex % 2 === 0) { sex = 2 } else { sex = 1 }
      this.formdata.gender = sex
      let date = new Date()
      let getMonth2 = date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1))
      this.formdata.patAge = age === 0 ? this.reduMonths(getMonth, getMonth2) : age + '岁'
      this.formdata.patBirthday = birth
      console.log('checkInfo=>this.formdata.patBirthday', this.formdata.patBirthday)
    },
    // 计算月差
    reduMonths(startMonth, endMonth) {
      let startY = startMonth.split('-')[0]
      let startM = startMonth.split('-')[1]
      let endY = endMonth.split('-')[0]
      let endM = endMonth.split('-')[1]
      startMonth = startY + startM
      endMonth = endY + endM
      if (startMonth > endMonth) {
        let reduY = startY - endY
        let reduM = startM - endM
        return reduY * 12 + reduM + '个月'
      } else if (startMonth < endMonth) {
        let reduY = endY - startY
        let reduM = endM - startM

        return reduY * 12 + reduM + '个月'
      } else {
        return 0 + '个月'
      }
    },
    submitForm(formdata) {
      this.$refs[formdata].validate((valid) => {
        if (valid) {
          var mobileRule = /^1[3456789]\d{9}$/
          if (this.formdata.patTelephone != '') {
            if (!mobileRule.test(this.formdata.patTelephone)) {
              this.$message.warning('请输入正确手机码号！')
              return
            }
          }
          this.formdata.idCard && this.checkInfo(this.formdata.idCard)
          // console.log('formdata====>', formdata)
          console.log('submitForm=>this.formdata.patBirthday', this.formdata.patBirthday)
          console.log('this.formdata.idCard', this.formdata.idCard)
          const patBirthday = this.formdata.idCard != '' ? this.formdata.patBirthday : this.formdata.birthDate
          console.log('submitForm=>patBirthday', patBirthday)
          let data = {
            hospitalCode: this.formdata.hospitalCode,
            accessNo: this.formdata.accessNo,
            patName: this.formdata.patName,
            patSex: this.formdata.gender === 1 ? '男' : this.formdata.gender === 2 ? '女' : '',
            patientAge: this.formdata.patientAge,
            patAge: this.formdata.patAge,
            patBirthday: dateFormatter(new Date(patBirthday), false),
            patTelephone: this.formdata.patTelephone,
            wardName: this.formdata.wardName,
            idCard: this.formdata.idCard,
            wardnoCode: this.formdata.wardnoCode,
            wardno: this.formdata.wardName,
            sqdepCode: this.formdata.sqdepCode,
            sqdep: this.formdata.sqdep,
            doctorCode: this.formdata.doctorCode,
            doctor: this.formdata.doctor,
            bedno: this.formdata.bedno,
            // 新增字段
            nameEnglish: this.formdata.nameEnglish,
            price: parseFloat(this.formdata.price),
            exammark: this.formdata.exammark,
            clinicend: this.formdata.clinicdiagnosis,
            clinicinfo: this.formdata.diseasesHistory,
            privacyLevel: this.formdata.privacyLevel,
            radioDoctor: this.formdata.radioDoctor,
            treatmentType: this.formdata.treatmentType
          }
          // console.log('data', data)
          changepatexam(data).then(res => {
            if (res && res.code === 10000) {
              this.$message.success(res.message)
              this.$emit('changePatBasicInfo')
              this.patBasicInfoVisible = false
            } else {
              this.$message.warning(res.message)
            }
          })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    // 根据输入身份证号，自动填写 性别、生日、年龄
    idCardChange() {
      let id = this.formdata.idCard
      if (id && isIdCard(id)) {
        this.formdata.gender = sexById(id)
        this.formdata.birthDate = birthdayById(id)
        this.setAgeValApply(this.formdata.birthDate)
      }
    },
    birthDateChange() {
      console.log('birthDateChange === ', this.formdata.birthDate)
      if (this.formdata.birthDate != null) {
        this.setAgeValApply(dateFormatter(this.formdata.birthDate, false))
      } else {
        this.formdata.patientAge = ''
      }
    },
    getMonthDay(year, month) {
      let days = new Date(year, month + 1, 0).getDate()
      return days
    },
    // 根据出生日期计算年龄
    getAgeApply(strAge) {
      var birArr = strAge.split('-')
      var birYear = birArr[0]
      var birMonth = birArr[1] * 1
      var birDay = birArr[2]

      var d = new Date()
      var nowYear = d.getFullYear()
      var nowMonth = d.getMonth() + 1 // 记得加1
      var nowDay = d.getDate()
      var returnAge; var errFlag = false; var errMsg = ''
      if (birArr == null) {
        return {
          errFlag: true,
          errMsg: '',
          val: ''
        }
      }
      var dBir = new Date(birYear, birMonth - 1, birDay)
      if (dBir.getFullYear() == birYear && (dBir.getMonth() + 1) == birMonth && dBir.getDate() == birDay) {
        if (nowYear == birYear) {
          // 同年
          // returnAge = 0; //同年
          var MonthDiff = nowMonth - birMonth // 计算月
          if (MonthDiff >= 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#D'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else if (nowMonth == birMonth + 1) {
              var preMonthDays = this.getMonthDay(birYear, birMonth)
              let dayDiff = nowDay + preMonthDays - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#D'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else {
              returnAge = MonthDiff + 1 + '#M'
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge
          }
        } else {
          // 不同年
          var ageDiff = nowYear - birYear // 计算年
          if (ageDiff > 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff < 0) {
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#Y'
                } else {
                  returnAge = 11 + '#M'
                }
              } else {
                returnAge = ageDiff + '#Y'
              }
            } else {
              var monthDiff = nowMonth - birMonth // 计算月
              if (monthDiff < 0) {
                // returnAge = ageDiff - 1;
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#Y'
                } else {
                  returnAge = Math.abs(nowMonth - birMonth + 12) + '#M'
                }
              } else {
                returnAge = ageDiff + '#Y'
              }
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'// 返回-1 表示出生日期输入错误 晚于今天
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge + '#Y'
          }
        }
      } else {
        return {
          errFlag: true,
          errMsg: '输入的日期格式错误！',
          val: ''
        }
      }
    },
    getTreatmentType() {
      /* 项目属性列表 */
      let params = {
        hospitalCode: this.hospitalCode,
        Type: '治疗类型'
        // modality: this.ruleForm.modality
      }
      return new Promise(resolve => {
        getItemGroupList(params).then((res) => {
          if (res.code === 10000) {
            this.treatmentTypeOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getRadioDoctor() {
      /* 项目属性列表 */
      let params = {
        hospitalCode: this.hospitalCode,
        Type: '检查技师'
        // modality: this.ruleForm.modality
      }
      return new Promise(resolve => {
        getItemGroupList(params).then((res) => {
          if (res.code === 10000) {
            this.radioDoctorOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    setAgeValApply(strAge) {
      const regex = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{3}[\dXx]$/
      const match = this.formdata.idCard.match(regex)
      let bornDay = ''
      if (match) {
        bornDay = `${match[2]}-${match[3]}-${match[4]}`
      }
      if (this.formdata.idCard != '' && bornDay != strAge) {
        let confirmMsg = '您选择的出生日期和身份证上的有冲突请问是否还要更改？'
        this.$confirm(confirmMsg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.formdata.birthDate = this.formdata.patBirthday.indexOf(bornDay) > -1 ? this.formdata.patBirthday : bornDay
        })
      }
      // console.log('setAgeValApply === ', strAge)
      var ageObj = this.getAgeApply(strAge)
      if (!ageObj.errFlag) {
        var ageArr = ageObj.val.split('#')
        this.formdata.patientAgeUnit = ageArr[1]
        this.formdata.patientAge = ageArr[0]
        this.$forceUpdate(0)
      } else if (ageObj.errMsg != '') {
        this.$alert(ageObj.errMsg, '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            this.formdata.birthDate = ''
          }
        })
        return false
      }
    },
    // 监听年龄变化，计算生日
    ageChange() {
      const bday = birthdayByAge(this.formdata.patientAge, this.formdata.patientAgeUnit)
      this.formdata.birthDate = bday
    },
    // 监听姓名变化，改变姓名拼音
    nameChange() {
      this.formdata.nameEnglish = window.pinyinUtil.getCorrectName(this.formdata.patName)
    },
    getParamsString(data) {
      const d = Object.keys(data).map(k => { return `${k}=${data[k]}` })
      return d.join('&')
    },
    refreshDate(date) {
      this.formdata.birthDate = date.split(' ')[0]
      this.setAgeValApply(this.formdata.birthDate)
    },
    resetForm(idCard) {
      this.$nextTick(() => {
        this.$refs['formdata'].clearValidate()
      })
    },
    // handleInput(value) {
    //   let id = value
    //   if (id.length === 18) {
    //     this.idCardChange()
    //   }
    //   // if (isIdCard(id)) {
    //   //   console.log(isIdCard(id))
    //   // }
    // },
    nameInput(value) {
      this.nameChange()
    },
    priceInput(value) {
      let reg = new RegExp(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/)
      return reg.test(value)
    }
    // copy() {
    //   this.idCardChange()
    // }
  }
}
</script>
<style scoped>

.el-row /deep/ .el-form-item{
  margin-bottom: 15px;
}

.el-row div:nth-child(5) /deep/ .el-form-item__label{
  line-height: 32px;
}

.el-row div:nth-child(6) /deep/ .el-form-item__label{
  line-height: 32px;
}

.el-row div:nth-child(6) /deep/ .el-form-item__content{
  line-height: 30px;
}
</style>
